// 运行时配置
import TabsLayout from '@/components/TabsLayout';
import { getUserInfo, logout } from '@/services/user';
import { PermissionUtils } from '@/utils/permission';
import { RolePermissionVo } from '@/types/permission';
import {
  AppstoreOutlined,
  HomeOutlined,
  LogoutOutlined,
  SettingOutlined,
  UserOutlined,
} from '@ant-design/icons';
import { history } from '@umijs/max';
import { Avatar, Dropdown, message } from 'antd';
import { stringify } from 'querystring';
import { errorConfig } from '../config/requestErrorConfig';
import { loginPath } from './constants';

// 定义类型
interface CurrentUser {
  [key: string]: any;
  permissions?: {
    menuPermissions: string[];
    buttonPermissions: string[];
  };
  menus?: any[];
}

interface InitialState {
  fetchUserInfo: () => Promise<any>;
  fetchUserPermissions: () => Promise<RolePermissionVo>;
  currentUser?: CurrentUser;
}

export async function getInitialState(): Promise<InitialState> {
  const fetchUserInfo = async () => {
    try {
      const userInfo = await getUserInfo();
      return userInfo;
    } catch (error) {
      console.error('获取用户信息失败:', error);
      return null;
    }
  };

  const fetchUserPermissions = async () => {
    try {
      return await PermissionUtils.getUserPermissions();
    } catch (error) {
      console.error('获取权限失败:', error);
      return {
        menus: [],
        userPermission: {
          menuPermissions: [],
          buttonPermissions: []
        }
      };
    }
  };

  // 检查是否为登录相关页面
  const { location } = history;
  if (location.pathname !== loginPath && location.pathname !== '/find') {
    const token = sessionStorage.getItem('token');

    if (!token) {
      history.push(loginPath);
      return { fetchUserInfo, fetchUserPermissions, currentUser: undefined };
    }

    try {
      // 并行获取用户信息和权限
      const [userInfo, permissions] = await Promise.all([
        fetchUserInfo(),
        fetchUserPermissions()
      ]);

      return {
        fetchUserInfo,
        fetchUserPermissions,
        currentUser: {
          ...userInfo,
          permissions: permissions.userPermission,
          menus: permissions.menus,
        },
      };
    } catch (error) {
      console.error('获取用户信息或权限失败:', error);
      return {
        fetchUserInfo,
        fetchUserPermissions,
        currentUser: {
          permissions: { menuPermissions: [], buttonPermissions: [] },
          menus: []
        }
      };
    }
  }

  return { fetchUserInfo, fetchUserPermissions, currentUser: undefined };
}

export const layout = ({ initialState }: any) => {
  const iconMap: Record<string, React.ReactNode> = {
    AppstoreOutlined: <AppstoreOutlined />,
    SettingOutlined: <SettingOutlined />,
    UserOutlined: <UserOutlined />,
    HomeOutlined: <HomeOutlined />,
  };

  const mapMenusToMenuData = (menus: any[] = []): any[] => {
    const sorted = [...menus].sort((a, b) => (a.sortNo || 0) - (b.sortNo || 0));
    return sorted.map((menu) => {
      const item: any = {
        name: menu.name,
        path: menu.path,
        icon: menu.icon ? iconMap[menu.icon] : undefined,
        hideInMenu: menu.hidden === 1,
      };
      if (Array.isArray(menu.children) && menu.children.length > 0) {
        item.children = mapMenusToMenuData(menu.children);
      }
      return item;
    });
  };

  return {
    layout: 'mix',
    logo: 'https://img.alicdn.com/tfs/TB1YHEpwUT1gK0jSZFhXXaAtVXa-28-27.svg',
    title: '后台管理系统',
    menu: {
      locale: false,
      request: async (_params: any, defaultMenuData: any[]) => {
        const menus = initialState?.currentUser?.menus;
        if (Array.isArray(menus) && menus.length > 0) {
          const resMenus = mapMenusToMenuData(menus);
          return resMenus;
        }
        return defaultMenuData;
      },
    },
    headerTitleRender: (logo: React.ReactNode) => (
        <div style={{ display: 'flex', alignItems: 'center', width: '256px' }}>
          <span>{logo}</span>
          <span style={{ lineHeight: '18px', fontSize: '14px', paddingLeft: '10px' }}>
          后台管理系统
        </span>
        </div>
    ),
    actionsRender: (props: any) => {
      if (props.isMobile) return [];

      const handleLogout = async () => {
        try {
          await logout();
          sessionStorage.clear();
          localStorage.removeItem('userPermissions');
          // 清除权限缓存
          PermissionUtils.clearCache();
          message.success('退出登录成功！');

          const { search, pathname } = window.location;
          const urlParams = new URLSearchParams(window.location.search);
          const redirect = urlParams.get('redirect');

          if (window.location.pathname !== loginPath && !redirect) {
            history.replace({
              pathname: loginPath,
              search: stringify({ redirect: pathname + search }),
            });
          }
        } catch (error) {
          message.error('退出登录失败，请重试！');
        }
      };

      return [
        <Dropdown
            key="user"
            menu={{ items: [{ key: 'logout', icon: <LogoutOutlined />, label: '退出登录', onClick: handleLogout }] }}
        >
          <div style={{ display: 'flex', alignItems: 'center', padding: '0 12px', cursor: 'pointer' }}>
            <Avatar
                size="small"
                src={initialState?.currentUser?.avatar || 'https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png'}
                style={{ marginRight: '8px' }}
            />
            <span>{initialState?.currentUser?.account || '未登录'}</span>
          </div>
        </Dropdown>,
      ];
    },
    menuItemRender: (menuItemProps: any, defaultDom: any) => {
      if (menuItemProps.isUrl || !menuItemProps.path) return defaultDom;
      return <a onClick={() => history.push(menuItemProps.path)}>{defaultDom}</a>;
    },
    onMenuHeaderClick: (e: React.MouseEvent<HTMLDivElement>) => {
      e.stopPropagation();
      e.preventDefault();
      history.push('/');
    },
    headerContentRender: () => <TabsLayout />,
  };
};

export const request = {
  ...errorConfig,
};